package eventHandling;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import eventHandling.EventTyp.Type;

/**
 * This class is an implementation of the event-bus-pattern. A Callback for a
 * event can be registered and is called when somebody fires this event.
 * 
 * @author sloth42
 * 
 */
public class EventBus {

	public HashMap<Type, ArrayList<Callback>> eventActionMapper = new HashMap<Type, ArrayList<Callback>>();


	/**
	 * Fire a special event.
	 * @param type The type of the event
	 */
	public void fireEvent(Type type) {
		ArrayList<Callback> callbacks = eventActionMapper.get(type);
		if (callbacks != null) {
			Iterator<Callback> iter = callbacks.iterator();
			while (iter.hasNext()) {
				iter.next().actionPerformed();
			}

		}
	}

	/**
	 * Register a Callback with the matching EventTyp.
	 * @param type The type of the event
	 * @param callback the Callback
	 */
	public void register(Type type, Callback callback) {
		ArrayList<Callback> callbacks = eventActionMapper.get(type);
		if (callbacks == null) {
			callbacks = new ArrayList<Callback>();
			callbacks.add(callback);
		} else {
			callbacks.add(callback);
		}
		eventActionMapper.put(type, callbacks);
	}

}